//
//  StatusPictureView.swift
//  微博
//
//  Created by admin on 2018/3/28.
//  Copyright © 2018年 xm. All rights reserved.
//

import UIKit

class StatusPictureView: UIView { 
    
    @IBOutlet weak var statusPictureViewHCons: NSLayoutConstraint!
    
    var homeStatusViewModel:HomeStatusViewModel?{
        didSet{
            
            reSetUIByData()
            
            for v in subviews {
                v.isHidden=true//隐藏所有图片视图
            }
            
            //遍历设置图像
            var index=0
            for url in homeStatusViewModel?.picModelList ?? [] {
                let iv = subviews[index] as! UIImageView
                
                //4张图像处理，跳过一个
                if index == 1 &&
                    homeStatusViewModel?.picModelList?.count == 4{
                    index += 1
                }
                
                iv.sd_setImage(urlString: url.thumbnail_pic, placeholderImage: nil)
                index += 1
                iv.isHidden=false
            }
        }
    }
    
    override func awakeFromNib() {
        super.awakeFromNib()
        
        setupUI()
    }
    
    
    func setupUI() {
        backgroundColor = superview?.backgroundColor
        //设置超出部分不显示
        clipsToBounds=true
        let count = 3
        //定义第一张图的位置大小
        let rect = CGRect(x: 0,
                        y: statusPictureViewOutMargin,
                        width: statusPictureItemWith,
                        height: statusPictureItemWith)
        
        for i in 0..<count * count {
            let iv=UIImageView()
            
            let row = CGFloat(i / count)
            
            let col=CGFloat(i % count)
            
            let xOffset = col * (statusPictureItemWith + statusPictureViewinMargin)
            let yOffset = row * (statusPictureItemWith + statusPictureViewinMargin)
            iv.frame = rect.offsetBy(dx: xOffset, dy: yOffset)
            addSubview(iv)
        }
    }
    
    /// 根据数据调整UI
    func reSetUIByData() {
        //设置配图视图的高度
        statusPictureViewHCons.constant=homeStatusViewModel?.statusPictureViewSize.height ?? 0
        let iv = subviews[0] as! UIImageView
        if (homeStatusViewModel?.picModelList?.count == 1){//单张图，最大显示
            iv.frame=CGRect(x: 0,
                            y: statusPictureViewOutMargin,
                            width:homeStatusViewModel?.statusPictureViewSize.width ?? 0 - statusPictureViewOutMargin,
                            height:statusPictureViewHCons.constant - statusPictureViewOutMargin)
        }else{//多张图
            iv.frame=CGRect(x: 0,
                            y: statusPictureViewOutMargin,
                            width: statusPictureItemWith,
                            height:statusPictureItemWith)
        }
    }
    
}
